import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { getAllPageConfigs } from '@/utils/page-config'
import type { PageConfig } from '@/types/page-config'

// 动态导入所有 views 目录下的 .vue 文件
const modules = import.meta.glob('../views/**/*.vue')
// 动态导入所有页面配置文件
const configModules = import.meta.glob('../views/**/config.ts', { eager: true })

// 获取页面配置
const getPageConfig = (filePath: string): PageConfig | null => {
  const configPath = `../views/${filePath}/config.ts`
  const configModule = configModules[configPath] as { default: PageConfig } | undefined
  return configModule?.default || null
}

// 生成动态路由
const generateRoutes = (): RouteRecordRaw[] => {
  const routes: RouteRecordRaw[] = []

  for (const path in modules) {
    // 提取文件路径信息
    const pathMatch = path.match(/\.\.\/views\/(.+)\.vue$/)
    if (!pathMatch) continue

    const filePath = pathMatch[1]
    const segments = filePath.split('/')
    const fileName = segments[segments.length - 1]
    
    // 跳过以 _ 开头的文件（私有组件）
    if (fileName.startsWith('_')) continue

    // 生成路由路径
    let routePath = '/' + filePath.toLowerCase()
    
    // 处理 index 文件作为根路径
    if (fileName.toLowerCase() === 'index') {
      routePath = segments.length === 1 ? '/' : '/' + segments.slice(0, -1).join('/').toLowerCase()
    }

    // 生成路由名称
    const routeName = filePath.replace(/\//g, '-').replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()

    // 获取页面配置
    const pageConfig = getPageConfig(segments.slice(0, -1).join('/'))
    
    // 生成页面标题（优先使用配置文件中的标题）
    const title = pageConfig?.title || fileName
      .replace(/([a-z])([A-Z])/g, '$1 $2')
      .replace(/^\w/, c => c.toUpperCase())

    routes.push({
      path: routePath,
      name: routeName,
      component: modules[path],
      meta: { 
        title,
        filePath: filePath,
        ...pageConfig?.meta,
        pageConfig
      }
    })
  }

  return routes.sort((a, b) => {
    const aOrder = a.meta?.pageConfig?.order || 999
    const bOrder = b.meta?.pageConfig?.order || 999
    if (aOrder !== bOrder) return aOrder - bOrder
    
    if (a.path === '/') return -1
    if (b.path === '/') return 1
    return a.path.localeCompare(b.path)
  })
}

const routes = generateRoutes()

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

router.beforeEach((to, from, next) => {
  next()
})

export default router
export { generateRoutes }